"""
测试HTTP服务器工具
"""

import threading
import time
import requests
from com.tools.Http_Utils import HTTPServerTool


def test_http_server():
    """
    测试HTTP服务器工具
    """
    # 创建服务器实例
    server = HTTPServerTool(host='localhost', port=8080)
    
    # 设置响应规则
    server.set_response_rule('GET', lambda data: {'message': 'Hello from GET'})
    server.set_response_rule('POST', lambda data: {'message': 'Hello from POST', 'received': data.get('test', 'none')})
    
    # 设置延迟
    server.set_delay('POST', 0.5)
    
    # 设置字段响应
    server.set_field_response('action', 'login', {'status': 'success', 'user': 'test'})
    
    # 添加条件
    server.add_condition(lambda data: 'Authorization' not in data.get('headers', {}) or 
                        data['headers']['Authorization'] == 'Bearer test')
    
    # 在后台线程中启动服务器
    server_thread = threading.Thread(target=server.start)
    server_thread.daemon = True
    server_thread.start()
    
    # 等待服务器启动
    time.sleep(1)
    
    try:
        # 测试GET请求
        print("测试GET请求:")
        response = requests.get('http://localhost:8080/')
        print(f"状态码: {response.status_code}")
        print(f"响应: {response.json()}")
        print()
        
        # 测试POST请求
        print("测试POST请求:")
        response = requests.post('http://localhost:8080/', json={'test': 'data'})
        print(f"状态码: {response.status_code}")
        print(f"响应: {response.json()}")
        print()
        
        # 测试带字段的POST请求
        print("测试带字段的POST请求:")
        response = requests.post('http://localhost:8080/', json={'action': 'login'})
        print(f"状态码: {response.status_code}")
        print(f"响应: {response.json()}")
        print()
        
        # 测试带条件的请求
        print("测试带条件的请求:")
        response = requests.get('http://localhost:8080/', headers={'Authorization': 'Bearer test'})
        print(f"状态码: {response.status_code}")
        print(f"响应: {response.json()}")
        print()
        
        print("所有测试完成!")
        
    except Exception as e:
        print(f"测试过程中出错: {e}")
    
    finally:
        # 停止服务器
        server.stop()


if __name__ == "__main__":
    test_http_server()